//
//  ViewController.m
//  掌上宏力
//
//  Created by admin on 17/1/13.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "MainTabbarController.h"
#import "PhoneBookViewController.h"
#import "FindViewController.h"
#import "MeViewController.h"
#import "HomeViewController.h"
#import "WJTouchID.h"
#import "CarsTBViewController.h"
#import "RemindNewsViewController.h"
#import "LoginController.h"


@interface MainTabbarController ()<WJTouchIDDelegate>

@property (nonatomic,strong) WJTouchID *touchID;

@property (nonatomic,assign) BOOL currentTouchId;

@property (nonatomic,strong) UIView *hideView;
@property (nonatomic,strong) UIAlertController *touchIdHUD;

@property (nonatomic,copy) NSString *states;

@end

@implementation MainTabbarController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initParameters];
    if ([NetWorker sharedNetWorker].isTouchId) {
        _hideView.hidden = NO;
        NetWorker.sharedNetWorker.isLogin = YES;
        [self.touchID startWJTouchIDWithMessage:WJNotice(@"按下HOME键验证指纹信息", @"The Custom Message") fallbackTitle:WJNotice(@"输入密码", @"Fallback Title") delegate:self];
    }else{
        [self setChildViewControllers];
    }
    
    [self receiveNotifications];
}
//接收通知
-(void)receiveNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setChildViewControllers) name:setViews object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToCarsViewC) name:cars object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToRemindViewC) name:remind object:nil];
    
    //过期登录判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(expriedLogin) name:expriLogin object:nil];
    
    //后台启动，判断touchid
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(judgeTouchId) name:touchId object:nil];
}
//初始化参数
-(void)initParameters{
    _states = setViews;
    if (_hideView == nil) {
        _hideView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        _hideView.backgroundColor = [UIColor whiteColor];
        _hideView.hidden = YES;
        [self.view addSubview:_hideView];
//        [self.view bringSubviewToFront:_hideView];
    }
   
    WJTouchID *touchid = [[WJTouchID alloc]init];
    self.touchID = touchid;
}
//过期登录
-(void)expriedLogin{
    [self judgeTouchId];
    if ([_states isEqualToString:@""]) {
        _hideView.hidden = NO;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"登录已过期，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        [self performSelector:@selector(goToLogin) withObject:nil afterDelay:1.0];
    }
    
}
-(void)goToLogin{
    //超时，删除用户登录信息
    User *user = [User currentUser];
    user.password = @"";
    [[LoginInfoTool sharedLoginInfoTool] clearLoginInfo];
    [LoginInfoTool sharedLoginInfoTool].currentUser = user;
    [NetWorker sharedNetWorker].isLogin = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    [self presentViewController:[[LoginController alloc] init] animated:YES completion:nil];
    [self performSelector:@selector(dismissHideViewAfterDelay) withObject:nil afterDelay:1.0];
}
-(void)dismissHideViewAfterDelay{
    _hideView.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)pushToCarsViewC{
    _states = cars;
    [self setSelectedIndex:2];
    UINavigationController *nav = self.childViewControllers[2];
    CarsTBViewController *carsV = [[CarsTBViewController alloc] init];
    carsV.hidesBottomBarWhenPushed = YES;
    [nav pushViewController:carsV animated:YES];
}
-(void)pushToRemindViewC{
    _states = remind;
    [self setSelectedIndex:2];
    UINavigationController *nav = self.childViewControllers[2];
    RemindNewsViewController *remindV = [[RemindNewsViewController alloc] init];
    remindV.hidesBottomBarWhenPushed = YES;
    [nav pushViewController:remindV animated:YES];
}

//判断指纹解锁
-(void)judgeTouchId{
    if ([NetWorker sharedNetWorker].isTouchId) {
        _hideView.hidden = NO;
        NetWorker.sharedNetWorker.isLogin = YES;
        
        //在这里去掉之前的密码输入框
        [_touchIdHUD dismissViewControllerAnimated:YES completion:nil];
        
        [self.touchID startWJTouchIDWithMessage:WJNotice(@"按下HOME键验证指纹信息", @"The Custom Message") fallbackTitle:WJNotice(@"输入密码", @"Fallback Title") delegate:self];
    }
}

//弹出输入密码的提示框
-(void)showInputPWDHUD{
    if (_touchIdHUD == nil) {
        _touchIdHUD = [UIAlertController alertControllerWithTitle:@"输入密码" message:@"请输入\"掌上宏力\"的登录密码" preferredStyle:UIAlertControllerStyleAlert];
        [_touchIdHUD addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.secureTextEntry = YES;
        }];
        
        [_touchIdHUD addAction:[UIAlertAction actionWithTitle:@"返回Touch ID" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.touchID startWJTouchIDWithMessage:WJNotice(@"按下HOME键验证指纹信息", @"The Custom Message") fallbackTitle:WJNotice(@"输入密码", @"Fallback Title") delegate:self];
        }]];
        
        [_touchIdHUD addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UITextField *pwdTF = _touchIdHUD.textFields.firstObject;
            if ([pwdTF.text isEqualToString:[User currentUser].password]) {
                _hideView.hidden = YES;
            }else{
                _touchIdHUD.title = @"密码验证失败";
                _touchIdHUD.message = @"请重新输入\"掌上宏力\"的登录密码";
                [self presentViewController:_touchIdHUD animated:YES completion:nil];
            }
            
        }]];
    }
    
    [self presentViewController:_touchIdHUD animated:YES completion:nil];
}


/**
 *  TouchID验证成功
 *
 *  (English Comments) Authentication Successul  Authorize Success
 */
- (void) WJTouchIDAuthorizeSuccess {
    if ([_states isEqualToString:setViews]) {
        [self setChildViewControllers];
    }
    _hideView.hidden = YES;
}

/**
 *  TouchID验证失败
 *
 *  (English Comments) Authentication Failure
 */
- (void) WJTouchIDAuthorizeFailure {
    [self showInputPWDHUD];
}
/**
 *  取消TouchID验证 (用户点击了取消)
 *
 *  (English Comments) Authentication was canceled by user (e.g. tapped Cancel button).
 */
- (void) WJTouchIDAuthorizeErrorUserCancel {
    [self showInputPWDHUD];
}

/**
 *  在TouchID对话框中点击输入密码按钮
 *
 *  (English Comments) User tapped the fallback button
 */
- (void) WJTouchIDAuthorizeErrorUserFallback {
    [self showInputPWDHUD];
}

/**
 *  在验证的TouchID的过程中被系统取消 例如突然来电话、按了Home键、锁屏...
 *
 *  (English Comments) Authentication was canceled by system (e.g. another application went to foreground).
 */
- (void) WJTouchIDAuthorizeErrorSystemCancel {
//    [self showInputPWDHUD];
}

/**
 *  无法启用TouchID,设备没有设置密码
 *
 *  (English Comments) Authentication could not start, because passcode is not set on the device.
 */
- (void) WJTouchIDAuthorizeErrorPasscodeNotSet {
    
}

/**
 *  设备没有录入TouchID,无法启用TouchID
 *
 *  (English Comments) Authentication could not start, because Touch ID has no enrolled fingers
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotEnrolled {
    
}

/**
 *  该设备的TouchID无效
 *
 *  (English Comments) Authentication could not start, because Touch ID is not available on the device.
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotAvailable {
}

/**
 *  多次连续使用Touch ID失败，Touch ID被锁，需要用户输入密码解锁
 *
 *  (English Comments) Authentication was not successful, because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite.
 *
 */
- (void) WJTouchIDAuthorizeLAErrorTouchIDLockout {
    [self showInputPWDHUD];
}

/**
 *  当前软件被挂起取消了授权(如突然来了电话,应用进入前台)
 *
 *  (English Comments) Authentication was canceled by application (e.g. invalidate was called while authentication was inprogress).
 *
 */
- (void) WJTouchIDAuthorizeLAErrorAppCancel {
    _hideView.hidden = YES;
    
}

/**
 *  当前软件被挂起取消了授权 (授权过程中,LAContext对象被释)
 *
 *  (English Comments) LAContext passed to this call has been previously invalidated.
 */
- (void) WJTouchIDAuthorizeLAErrorInvalidContext {
    [self dismissViewControllerAnimated:YES completion:nil];
    _hideView.hidden = YES;
    
}
/**
 *  当前设备不支持指纹识别
 *
 *  (English Comments) The current device does not support fingerprint identification
 */
-(void)WJTouchIDIsNotSupport {
    
}


-(void)setChildViewControllers{
    HomeViewController *home = [[HomeViewController alloc] init];
    UINavigationController *homeNav = [[UINavigationController alloc] initWithRootViewController:home];
    homeNav.tabBarItem.title = @"首页";
    homeNav.tabBarItem.image = [UIImage imageNamed:@"tab_home"];
    homeNav.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_home_H"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    PhoneBookViewController *phoneBook = [[PhoneBookViewController alloc] init];
    UINavigationController *PhoneBookNav = [[UINavigationController alloc] initWithRootViewController:phoneBook];
    PhoneBookNav.tabBarItem.title = @"通讯录";
    PhoneBookNav.tabBarItem.image = [UIImage imageNamed:@"tab_phone"];
    PhoneBookNav.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_phone_H"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    FindViewController *find = [[FindViewController alloc] init];
    UINavigationController *findNav = [[UINavigationController alloc] initWithRootViewController:find];
    findNav.tabBarItem.title = @"发现";
    findNav.tabBarItem.image = [UIImage imageNamed:@"tab_find"];
    findNav.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_find_H"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    MeViewController *my = [[MeViewController alloc] init];
    UINavigationController *myNav = [[UINavigationController alloc] initWithRootViewController:my];
    myNav.tabBarItem.title = @"我的";
    myNav.tabBarItem.image = [UIImage imageNamed:@"tab_mine"];
    myNav.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_mine_H"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.tabBar.tintColor = [UIColor colorWithRed:29/255.0 green:138/255.0 blue:44/255.0 alpha:1.0];
    self.viewControllers = @[homeNav,PhoneBookNav,findNav,myNav];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
